package com.ruoyi.web.controller.maintenance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.github.pagehelper.PageInfo;
import com.ruoyi.qcsystem.domain.entity.QualityFistConfirmation;
import com.ruoyi.ruoyimaintenance.domain.entity.MaintenanceDL;
import com.ruoyi.ruoyimaintenance.domain.entity.MaintenanceLogdata;
import com.ruoyi.ruoyimaintenance.service.MaintenanceLogdataService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/MaintenanceLogdataController")
public class MaintenancelogdataController {

    @Autowired
    MaintenanceLogdataService maintenanceLogdataService;



    Integer line;
    String machineNumber;
    String headNumber;
    String timeStar;
    String timeEnd;

    @GetMapping("/maintenanceLogdataBySearch")
    PageInfo<MaintenanceLogdata> maintenanceLogdataBySearch(
            @RequestParam(defaultValue = "1")Integer pageNub,
            @RequestParam(defaultValue = "10")Integer pageSize,
            @RequestParam(defaultValue = "")Integer line,
            @RequestParam(defaultValue = "")String machineNumber,
            @RequestParam(defaultValue = "")String headNumber,
            @RequestParam(defaultValue = "")String timeStar,
            @RequestParam(defaultValue = "")String timeEnd
    ){
        this.line =line;
        this.machineNumber=machineNumber;
        this.headNumber=headNumber;
        this.timeStar=timeStar;
        this.timeEnd=timeEnd;
        return maintenanceLogdataService.maintenanceLogdataBySearch(pageNub, pageSize, line, machineNumber, headNumber, timeStar, timeEnd);
    }

    @GetMapping("/maintenanceDLBySearch")
    PageInfo<MaintenanceDL> maintenanceDLBySearch(
            @RequestParam(defaultValue = "1")Integer pageNub,
            @RequestParam(defaultValue = "10")Integer pageSize,
            @RequestParam(defaultValue = "")Integer line,
            @RequestParam(defaultValue = "")String machineNumber,
            @RequestParam(defaultValue = "")String headNumber
    ){
        return maintenanceLogdataService.maintenanceDLBySearch(pageNub,pageSize,line,machineNumber,headNumber);
    }

    @PostMapping("/addMaintenanceLogdata")
    int addMaintenanceLogdata(@Validated @RequestBody MaintenanceDL maintenanceDL){

        return maintenanceLogdataService.addMaintenanceLogdata(maintenanceDL);
    }

    @PostMapping("/updateMaintenanceLogdata")
    int updateMaintenanceLogdata(@Validated @RequestBody MaintenanceDL maintenanceDL){
        long id = maintenanceDL.getId();
        String maintenanceDate = maintenanceDL.getMaintenanceDate();
        String headCount = maintenanceDL.getHeadCount();
        String maintenanceItem = maintenanceDL.getMaintenanceItem();
        String maintenanceResult = maintenanceDL.getMaintenanceResult();
        String implementer = maintenanceDL.getImplementer();
        String abnormalDescription = maintenanceDL.getAbnormalDescription();
        return maintenanceLogdataService.updateMaintenanceLogdata(id,maintenanceDate,headCount,maintenanceItem,maintenanceResult,implementer,abnormalDescription);
    }

    @DeleteMapping("/deleteMaintenanceLogdata/{id}")
    int deleteMaintenanceLogdata(@PathVariable Long id){
        return maintenanceLogdataService.deleteMaintenanceLogdata(id);
    }

    @PostMapping("/handleExport")
    public void export(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("样品数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        List<MaintenanceDL> dataList=maintenanceLogdataService.queryMaintenanceDLList(line,machineNumber,headNumber,timeStar,timeEnd);

        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), MaintenanceDL.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {
                        // Add timestamp after last data row
                        if (!isHead && relativeRowIndex != null && relativeRowIndex == dataList.size() - 1) {
                            Sheet sheet = writeSheetHolder.getSheet();
                            int lastRowNum = sheet.getLastRowNum();
                            // 创建当前时间
                            Row timeRow = sheet.createRow(lastRowNum + 1);
                            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                            timeRow.createCell(0).setCellValue("导出时间:"+format);
                            // Merge cells if needed (columns 0-7)
                            sheet.addMergedRegion(new CellRangeAddress(
                                    lastRowNum + 1, // first row
                                    lastRowNum + 1, // last row
                                    0,              // first column
                                    7               // last column
                            ));
                        }
                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("样品列表").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

}
